package com.jcfk.eam.service.main;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.main.EamPointCheckDetailDao;
import com.jcfk.eam.domain.dto.main.EamPointCheckDetailDTO;
import com.jcfk.eam.domain.dto.main.EamPointCheckDetailImgDTO;
import com.jcfk.eam.domain.po.main.EamPointCheckDetail;
import com.jcfk.eam.domain.po.main.EamPointCheckDetailImg;
import com.jcfk.eam.domain.po.main.EamPointCheckOrder;
import com.jcfk.eam.domain.query.main.EamPointCheckDetailQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 资产点检工单明细
 *
 * @author yrl
 * @email
 * @date 2024-11-06
 */
@Service
public class EamPointCheckDetailService extends BaseService<EamPointCheckDetailDao, EamPointCheckDetail> {

    @Resource
    private EamPointCheckDetailImgService eamPointCheckDetailImgService;

    /**
     * EamPointCheckDetail分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamPointCheckDetailDTO> queryByPage(DataPage<EamPointCheckDetailDTO> page, EamPointCheckDetailQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamPointCheckDetail是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamPointCheckDetailDTO dto) {
        QueryWrapper<EamPointCheckDetail> queryWrapper = new QueryWrapper<>();

        return RetResult.ok();
    }

    /**
     * 插入资产点检工单明细
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamPointCheckDetailDTO dto) {

        // 保存
        EamPointCheckDetail item = new EamPointCheckDetail();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);
    }

    /**
     * 更新资产点检工单明细
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamPointCheckDetailDTO dto) {

        // 保存
        EamPointCheckDetail item = new EamPointCheckDetail();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }


    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamPointCheckDetail item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取资产点检工单明细信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamPointCheckDetailDTO get(String id) {
        // 查询数据
        EamPointCheckDetail item = this.baseMapper.selectById(id);
        EamPointCheckDetailDTO dto = new EamPointCheckDetailDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 资产点检工单明细批量保存
     *
     * @param dtos
     * @return StandardCodeDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<EamPointCheckDetailDTO> dtos, String orderId) {
        List<EamPointCheckDetail> insertList = new ArrayList<>();
        List<EamPointCheckDetail> updateList = new ArrayList<>();
        List<String> notDeleteIds = new ArrayList<>();

        for (EamPointCheckDetailDTO dto : dtos) {
            EamPointCheckDetail item = new EamPointCheckDetail();

            BeanUtils.copyProperties(dto, item);
            this.setDefaultValue(item);
            // 设置关联主键
            item.setOrderId(orderId);
            if (!StringUtils.isEmpty(dto.getId())) {
                notDeleteIds.add(dto.getId());
                updateList.add(item);
            } else {
                insertList.add(item);
            }
        }

        // 删除
        QueryWrapper<EamPointCheckDetail> queryWrapper = new QueryWrapper<>();
        if (notDeleteIds.size() > 0) queryWrapper.notIn("id", notDeleteIds);
        queryWrapper.lambda().eq(EamPointCheckDetail::getOrderId, orderId);
        this.remove(queryWrapper);

        // 保存新增
        if (insertList.size() > 0) this.saveBatch(insertList);

        // 保存更新
        if (updateList.size() > 0) this.updateBigBatch(updateList);
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamPointCheckDetailDTO>
     */
    public List<EamPointCheckDetailDTO> getList(EamPointCheckDetailQuery query) {
        // 查询条件
        QueryWrapper<EamPointCheckDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getOrderId()), EamPointCheckDetail::getOrderId, query.getOrderId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getSopItemId()), EamPointCheckDetail::getSopItemId, query.getSopItemId());
        // 查询数据
        List<EamPointCheckDetail> list = super.list(qw);

        return convertList(list, EamPointCheckDetailDTO.class);
    }

    /**
     * 根据主键获取资产点检工单明细信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        this.removeById(id);
    }

    public List<EamPointCheckDetailDTO> listIncludeImg(String orderId) {
        // 查询详情数据
        Wrapper<EamPointCheckDetail> eq = Wrappers.<EamPointCheckDetail>lambdaQuery()
                .eq(EamPointCheckDetail::getOrderId, orderId);
        List<EamPointCheckDetail> details = this.list(eq);
        if (details.size() == 0) {
            return new ArrayList<>();
        }
        // 查询所有detail的image
        List<EamPointCheckDetailImg> imageList = eamPointCheckDetailImgService.list(
                Wrappers.<EamPointCheckDetailImg>lambdaQuery()
                        .in(EamPointCheckDetailImg::getPointCheckDetailId, details.stream().map(EamPointCheckDetail::getId).collect(Collectors.toList()))
                        .eq(EamPointCheckDetailImg::getDeleted, 0));
        // 根据detailId分组
        Map<String, List<EamPointCheckDetailImg>> imgMap = imageList.stream().collect(Collectors.groupingBy(EamPointCheckDetailImg::getPointCheckDetailId));
        return details.stream().map(item -> {
            EamPointCheckDetailDTO dto = new EamPointCheckDetailDTO();
            BeanUtils.copyProperties(item, dto);
            // 查询图片
            List<EamPointCheckDetailImg> imgs = imgMap.get(item.getId());
            if (CollUtil.isNotEmpty(imgs))
                dto.setImages(convertList(imgs, EamPointCheckDetailImgDTO.class));
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 资产点检工单明细批量保存
     *
     * @param dtos
     * @return StandardCodeDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public List<EamPointCheckDetailDTO> saveBatchProductRecord(List<EamPointCheckDetailDTO> dtos, EamPointCheckOrder itemOrder) {
        List<EamPointCheckDetail> insertList = new ArrayList<>();
        List<EamPointCheckDetail> updateList = new ArrayList<>();
        List<String> notDeleteIds = new ArrayList<>();

        for (EamPointCheckDetailDTO dto : dtos) {
            EamPointCheckDetail item = new EamPointCheckDetail();

            BeanUtils.copyProperties(dto, item);
            this.setDefaultValue(item);
            // 设置关联主键
            item.setOrderId(itemOrder.getId());
            if (!StringUtils.isEmpty(dto.getId())) {
                notDeleteIds.add(dto.getId());
                updateList.add(item);
            } else {
                dto.setId(IdUtils.simpleUUID());
                item.setId(dto.getId());
                insertList.add(item);
            }
        }

        // 删除
        QueryWrapper<EamPointCheckDetail> queryWrapper = new QueryWrapper<>();
        if (notDeleteIds.size() > 0) queryWrapper.notIn("id", notDeleteIds);
        queryWrapper.lambda().eq(EamPointCheckDetail::getOrderId, itemOrder.getId());
        this.remove(queryWrapper);

        // 保存新增
        if (insertList.size() > 0) this.saveBatch(insertList);

        // 保存更新
        if (updateList.size() > 0) this.updateBigBatch(updateList);

        return dtos;
    }
}

